﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Reflection;
using System.Configuration;
using ConfigMgrTest;

namespace lxwmvc
{
    public enum huifu_lx
    {
        /// <summary>
        /// 充值
        /// </summary>
        chongzhi = 10,
        /// <summary>
        /// 解冻
        /// </summary>
        jiedong = 11,
        /// <summary>
        /// 冻结
        /// </summary>
        dongjie = 12,
        /// <summary>
        /// 提现
        /// </summary>
        tixian = 13,
        /// <summary>
        /// 商户带用户提现
        /// </summary>
        tixianshanghu = 14,
        /// <summary>
        /// 撤标
        /// </summary>
        chebiao = 15,
        /// <summary>
        /// 生利宝
        /// </summary>
        shenglibao = 16,
        /// <summary>
        /// 投标
        /// </summary>
        toubiao = 17,
        /// <summary>
        /// 方框
        /// </summary>
        fangkuan = 18,
        /// <summary>
        /// 换狂
        /// </summary>
        huankuan = 19,
        /// <summary>
        /// 商户转账
        /// </summary>
        zhuanzhuangshanghu = 20,
        /// <summary>
        /// 提现复核
        /// </summary>
        tixianfuhe =21,
        /// <summary>
        /// 异步对账
        /// </summary>
        duizhangyibu = 22,
        /// <summary>
        /// 查询交易状态
        /// </summary>
        chaxunjiaoyizhuangtai = 23,
        /// <summary>
        /// 提现对账
        /// </summary>
        tixianduizhang = 24,
        /// <summary>
        /// 债权转让
        /// </summary>
        zhaiquanzhuanrang = 25,
        /// <summary>
        /// 商户内部转账
        /// </summary>
        shanghuzhuangzhangneibu = 26
    }

    public class core_huifu
    {
        /// <summary>
        /// 汇付返回成功的标志
        /// </summary>
        public static string HUIFU_SUCCESS = "000";
        //public static string HUIFU_SUCCESS = "000";

        /// <summary>
        /// 获取交易的唯一订单编号
        /// </summary>
        /// <param name="lx"></param>
        /// <returns></returns>
        public static string getOrdId(huifu_lx lx)
        {
            var lxname = "_"+Enum.GetName(typeof(huifu_lx), lx);

            //获取订单编号 20150724000002
            var ordid = queryhelper.get(" execute  lxwGSN '" + lxname + "','','1','000001'").tostr() ;

            //长度18位
            return ordid.Substring(2, 6) + DateTime.Now.ToString("HHmm") + (int)lx + ordid.Substring(8);

            //yyMMddHHmm
        }

        static public bool ValidateInput(string inputStr)
        {
            string pattern = @"^[0-9]*$";
            Regex regex = new Regex(pattern);

            if (!regex.IsMatch(inputStr))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 保存汇付流水信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public static void saveHuiFuLiuShui(object obj)
        {
            supermodel sm = supermodel.create("hf");
            sm["rq"] = DateTime.Now;
            sm["leixing"] = obj.GetType().Name;
            sm["neirong"] = supermodel.create().fromModel(obj).ToString();
            sm.saveorupdate();
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public String Base64(string str)
        {
            byte[] byteStr = Encoding.UTF8.GetBytes(str.ToCharArray());
            return Convert.ToBase64String(byteStr);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public String DeBase64(string str)
        {
            byte[] decbuff = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(decbuff);
        }

        static public T Send<T>(dynamic sendobj)
        {           
            try
            {
                //商户私有域中包含中文须先以Base64加密再使用
                if (!ValidateInput(sendobj.MerPriv))
                {
                    byte[] byteStr = Encoding.UTF8.GetBytes(sendobj.MerPriv.ToCharArray());
                    sendobj.MerPriv = Convert.ToBase64String(byteStr);
                }
            }
            catch { }


            StringBuilder chkVal = new StringBuilder();
            string s = sendobj.ChkValue;
            s = s.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
            var arr = s.Split('+');
            foreach (string o in arr)
            {
                chkVal.Append(sendobj.GetType().GetField(o).GetValue(sendobj));
            }


            Console.WriteLine(chkVal.ToString());
            sendobj.ChkValue = chkVal.ToString();

            //私钥文件的位置(这里是放在了站点的根目录下)
            string merKeyFile = AppDomain.CurrentDomain.BaseDirectory + "MerPrK530302.key";
            //需要指定提交字符串的长度
            int len = Encoding.UTF8.GetBytes(sendobj.ChkValue).Length;
            StringBuilder sbChkValue = new StringBuilder(256);
            //加签
            int str = DllInterop.SignMsg("530302", merKeyFile, sendobj.ChkValue, len, sbChkValue);

            sendobj.ChkValue = sbChkValue.ToString();

            using (var client = new WebClient())
            {
                var values = new NameValueCollection();
                var fields = sendobj.GetType().GetFields();
                var r = "";
                foreach (var o in fields)
                {
                    values.Add(o.Name, o.GetValue(sendobj));
                    Console.WriteLine(o.Name+"=>"+o.GetValue(sendobj));
                    r += "&" + o.Name + "=" + o.GetValue(sendobj);
                }

                //组合的信息
                Console.WriteLine(r);

                string url = HuiFuArg.MerUrl;
                //同步发送form表单请求
                byte[] result = client.UploadValues(url, "POST", values);
                var retStr = Encoding.UTF8.GetString(result);
                //Response.Write(retStr);
                Console.WriteLine("ret=>" + retStr);

                dynamic t = (T)Activator.CreateInstance(typeof(T));
                dynamic ret = (T)FastJSON.ToObject(retStr, t);

                StringBuilder builder = new StringBuilder();

                string _s = t.ChkValue;
                _s = _s.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
                var _arr = _s.Split('+');
                if (_arr != null)
                {
                    foreach (string o in _arr)
                    {
                        if (o != "")
                        {
                            builder.Append(ret.GetType().GetField(o).GetValue(ret));
                        }
                    }
                }
                var msg = builder.ToString();
                ////验签
                string pgPubkFile = AppDomain.CurrentDomain.BaseDirectory + "PgPubk.key";
                int retOk = DllInterop.VeriSignMsg(pgPubkFile, msg, msg.Length, ret.ChkValue);


                ////如果返回值为0，代表验签成功；否则就为失败
                //if (retOk == 0)
                // {
                    //Response.Write("验签成功！");
                //}
                // else
                // {
                //     throw new Exception("验签失败！");
                //  }

                return ret;
            }
        }

        static public void Submit(dynamic sendobj)
        {
            try
            {
                //商户私有域中包含中文须先以Base64加密再使用
                if (!ValidateInput(sendobj.MerPriv))
                {
                    byte[] byteStr = Encoding.UTF8.GetBytes(sendobj.MerPriv.ToCharArray());
                    sendobj.MerPriv = Convert.ToBase64String(byteStr);
                }
            }
            catch { }

            StringBuilder sb = new StringBuilder();

            //<div style='display:none'>
            sb.AppendLine(@"<form id=""form1"" method=""post"" action='"+HuiFuArg.MerUrl+"'>");

            var fields = sendobj.GetType().GetFields();
            var b = false;
            foreach (var o in fields)
            {
                if (o.Name == "ChkValue")
                {
                    b = true;
                    continue;
                }
                sb.AppendLine(@" <input type=""hidden"" name=""" + o.Name + @""" value='" + o.GetValue(sendobj) + @"'/>");
            }

            if (b)
            {
                StringBuilder chkVal = new StringBuilder();
                string s = sendobj.ChkValue;
                s = s.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
                var arr = s.Split('+');
                foreach (string o in arr)
                {
                    chkVal.Append(sendobj.GetType().GetField(o).GetValue(sendobj));
                }

                sendobj.ChkValue = chkVal.ToString();

                //私钥文件的位置(这里是放在了站点的根目录下)
                string merKeyFile = AppDomain.CurrentDomain.BaseDirectory + "MerPrK530302.key";
                //需要指定提交字符串的长度
                int len = Encoding.UTF8.GetBytes(sendobj.ChkValue).Length;
                StringBuilder sbChkValue = new StringBuilder(256);
                //加签
                int str = DllInterop.SignMsg("530302", merKeyFile, sendobj.ChkValue, len, sbChkValue);

                sendobj.ChkValue = sbChkValue.ToString();
                sb.AppendLine(@" <input type=""hidden"" name=""ChkValue"" value=""" + sendobj.ChkValue + @"""/>");
            }


            //</div>
            sb.AppendLine(@"</form>

 <script>
       //3秒钟跳转
//setTimeout('form1.submit()',3000);
window.onload=function()
{
   form1.submit();
}
    </script>
");

            HttpContext.Current.Response.Write(sb.ToString());
      
        }

        static public void ReturnUrl(HttpContext context,string key,dynamic obj,bool show = false)
        {
            //商户实现后台方式时需要在页面上打印RECV_ORD_ID
            string RECVORDER_PREFIX = "RECV_ORD_ID_";
            var Request = context.Request; //HttpContext.Response.ContentType = "text/html";
            context.Response.ContentType = "text/html";

            if (Request.RequestType.ToUpper() == "POST")
            {
                int ret = 0;
                if (Request.Params != null)
                {
                    string s = obj.ChkValue;

                    var fields = obj.GetType().GetFields();
                    foreach (FieldInfo o in fields)
                    {
                        try
                        {
                            o.SetValue(obj, Request.Params[o.Name]);
                            if (o.Name.ToLower() == "MerPriv".ToLower())
                            {
                                //byte[] byteStr = Encoding.UTF8.GetBytes(Request.Params[o.Name].ToCharArray());
                                //sendobj.MerPriv = Convert.FromBase64String(Request.Params[o.Name]);

                                //设置
                                try
                                {
                                    o.SetValue(obj, int.Parse(Request.Params[o.Name]).ToString()
                                     );
                                }
                                catch
                                {
                                    o.SetValue(obj,
                                         Encoding.UTF8.GetString(
                                        Convert.FromBase64String(HttpUtility.UrlDecode(Request.Params[o.Name])))
                                        );
                                }
                                continue;
                            }
                        }
                        catch { }
                    }


                    StringBuilder chkVal = new StringBuilder();
                   
                    s = s.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
                    var arr = s.Split('+');
                    foreach (string o in arr)
                    {
                        if (o == "BgRetUrl")
                        {
                            string bgRetUrl = Request.Params["BgRetUrl"].ToString();
                            if (!string.IsNullOrWhiteSpace(bgRetUrl))
                            {
                                string decodeBgRetUrl = HttpUtility.UrlDecode(bgRetUrl);
                                chkVal.Append(decodeBgRetUrl);
                            }
                            continue;
                        }
                        if (o == "RetUrl")
                        {
                            string bgRetUrl = Request.Params["RetUrl"].ToString();
                            if (!string.IsNullOrWhiteSpace(bgRetUrl))
                            {
                                string decodeBgRetUrl = HttpUtility.UrlDecode(bgRetUrl);
                                chkVal.Append(decodeBgRetUrl);
                            }
                            continue;
                        }
                        if (o == "MerPriv")
                        {
                            string merPriv = Request.Params["MerPriv"].ToString();
                            if (!string.IsNullOrWhiteSpace(merPriv))
                            {
                                string decodeMerPriv = HttpUtility.UrlDecode(merPriv);
                                chkVal.Append(decodeMerPriv);
                            }
                            continue;
                        }
                        chkVal.Append(Request.Params[o]);
                    }

                    var msg = chkVal.ToString();
                    //验签
                    string PgPubkFile = AppDomain.CurrentDomain.BaseDirectory + "PgPubk.key";
                    ret = DllInterop.VeriSignMsg(PgPubkFile, msg, msg.Length, Request.Params["ChkValue"].ToString());
                }

                //保存流水
                saveHuiFuLiuShui(obj);

                //如果返回值为0，代表验签成功；否则就为失败
                if (ret == 0)
                {
                    //打印出来。
                    if(show)
                        context.Response.Write(RECVORDER_PREFIX + Request.Params[key].ToString());
                }
                else
                {
                    if (show)
                        context.Response.Write("验签失败！");
                }
            }
        }
    }
}